const app = getApp();
const https = require('../../utils/https.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    delBtnWidth: 140,
    startX: "",
    adminShow: true, //管理
    shopcarData: [],
    total: 0, //总金额    
    allsel: false, //全选      
    selarr: [], //选择的货物
    allNum: 0, //全部宝贝
    sumNumber: 0,
  },
  //商品总数量
  allGoods: function () {
    var allNum = 0
    var cart_list = this.data.cart_list;
    for (var i in cart_list) {
      allNum += parseInt(cart_list[i].buy_num)
    }
    this.setData({
      allNum: allNum
    })
  },
  touchS: function (e) {
    if (e.touches.length == 1) {
      this.setData({
        //设置触摸起始点水平方向位置
        startX: e.touches[0].clientX
      });
    }
  },
  touchM: function (e) {
    if (e.touches.length == 1) {
      //手指移动时水平方向位置
      var moveX = e.touches[0].clientX;
      //手指起始点位置与移动期间的差值
      var disX = this.data.startX - moveX;
      var delBtnWidth = this.data.delBtnWidth;
      var txtStyle = "";
      if (disX == 0 || disX < 0) { //如果移动距离小于等于0，说明向右滑动，文本层位置不变
        txtStyle = "left:0px";
      } else if (disX > 0) { //移动距离大于0，文本层left值等于手指移动距离
        txtStyle = "left:-" + disX + "px";
        if (disX >= delBtnWidth) {
          //控制手指移动距离最大值为删除按钮的宽度
          txtStyle = "left:-" + delBtnWidth + "px";
        }
      }
      //获取手指触摸的是哪一项
      var index = e.currentTarget.dataset.index;
      var list = this.data.cart_list;
      list[index].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        cart_list: list
      });
    }
  },
  touchE: function (e) {
    if (e.changedTouches.length == 1) {
      //手指移动结束后水平位置
      var endX = e.changedTouches[0].clientX;
      //触摸开始与结束，手指移动的距离
      var disX = this.data.startX - endX;
      var delBtnWidth = this.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      var txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "px" : "left:0px";
      //获取手指触摸的是哪一项
      var index = e.currentTarget.dataset.index;
      var list = this.data.cart_list;
      list[index].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        cart_list: list
      });
    }
  },
  //获取元素自适应后的实际宽度
  getEleWidth: function (w) {
    var real = 0;
    try {
      var res = wx.getSystemInfoSync().windowWidth;
      var scale = (750 / 2) / (w / 2); //以宽度750px设计稿做宽度的自适应
      real = Math.floor(res / scale);
      return real;
    } catch (e) {
      return false;
      // Do something when catch error
    }
  },
  initEleWidth: function () {
    var delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
    this.setData({
      delBtnWidth: delBtnWidth
    });
  },
  //点击删除按钮事件
  delGoodsCart: function (obj) {
    var that = this,
      cart_id = obj.currentTarget.dataset.cart_id;
    wx.showModal({
      title: '删除确认',
      content: '您确定要删除这个购物车记录吗？',
      success: function (sm) {
        if (sm.confirm) {
          https.post('delGoodsCart', {
            cart_id: cart_id
          }, false, '正在删除').then(res => {
            //更新购物车列表
            that.onShow();
          })
        } else if (sm.cancel) {}
      }
    })

  },
  /**
   * @xk 跳转
   * @param {} res 
   */
  goShopping_mall: function (res) {
    wx.switchTab({
      url: '/pages/shopping_mall/shopping_mall',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this,
      login_status = wx.getStorageSync('login_status');
    if (!login_status || login_status <= 0) {
      wx.showLoading({
        title: '请先进行登陆',
      })
      setTimeout(() => {
        wx.hideLoading({
          success: (res) => {
            wx.navigateTo({
              url: '/pages/grant/grant',
            })
          },
        })
      }, 1500);
    } else {
      that.setData({
        allsel: false
      })
      // 购物车列表
      that.getGoodsCart();
    }
    
  },
  /**
   * @xk 获取购物车列表
   */
  getGoodsCart() {
    var that = this,
      user_id = wx.getStorageSync('user_id');
    if (!user_id || user_id <= 0) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 1500,
      })
      that.getUserInfo();
      return;
    }
    https.post('getGoodsCart', {
      user_id: user_id
    }, false, '极速加载中').then(res => {
      that.setData({
        cart_list: res
      })
      that.allGoods();
    })
  },
  //点击全选  
  allcheckTap: function () {
    let shopcar = this.data.cart_list,
      allsel = !this.data.allsel; //点击全选后allsel变化
    for (let i = 0, len = shopcar.length; i < len; i++) {
      shopcar[i].check = allsel; //所有商品的选中状态和allsel值一样
    }
    this.data.selarr = allsel ? Object.assign([], shopcar) : []; //如果选中状态为true那么所有商品为选中状态，将物品加入选中变量，否则为空  
    this.setData({
      allsel: allsel,
      cart_list: shopcar,
      selarr: this.data.selarr
    });
    this.getTotal();
  },
  //点击单个选择按钮  
  checkTap: function (e) {
    let Index = e.currentTarget.dataset.index,
      shopcar = this.data.cart_list,
      selarr = this.data.selarr;
    shopcar[Index].check = !shopcar[Index].check || false;
    if (shopcar[Index].check) {
      selarr.push(shopcar[Index]);
    } else {
      for (let i = 0, len = selarr.length; i < len; i++) {
        if (shopcar[Index].id == selarr[i].id) {
          selarr.splice(i, 1);
          break;
        }
      }
    }
    this.setData({
      cart_list: shopcar,
      selarr: selarr,
    });
    this.judgmentAll(); //每次按钮点击后都判断是否满足全选的条件  
    this.getTotal();
  },
  //判断是否为全选  
  judgmentAll: function () {
    let shopcar = this.data.cart_list,
      shoplen = shopcar.length,
      lenIndex = 0; //选中的物品的个数    
    for (let i = 0; i < shoplen; i++) { //计算购物车选中的商品的个数    
      shopcar[i].check && lenIndex++;
    }
    this.setData({
      allsel: lenIndex == shoplen //如果购物车选中的个数和购物车里货物的总数相同，则为全选，反之为未全选    
    });
  },
  //计算总金额
  getTotal: function () {
    var that = this,
      total = 0.00,
      sumNumber = 0,
      cart_list = this.data.cart_list;
    cart_list.forEach(function (item, index) {
      if (item.check) {
        sumNumber += parseInt(item['buy_num']);
        total += parseInt(item['buy_num']) * item['goods_price'];
      }
    })
    that.setData({
      total: total,
      sumNumber: sumNumber
    })
  },
  //点击加减按钮  
  numchangeTap: function (obj) {
    let types = obj.currentTarget.dataset.types,
      Index = obj.currentTarget.dataset.index, //点击的商品下标值        
      shopcar = this.data.cart_list;
    switch (types) {
      case 'add':
        shopcar[Index].buy_num++; //对应商品的数量+1      
        break;
      case 'minus':
        shopcar[Index].buy_num--; //对应商品的数量-1      
        break;
    }
    this.setData({
      cart_list: shopcar,
    });
    this.allGoods();
    this.getTotal();
  },
  /**
   * @xk 提交购物车数据修改
   */
  goclearingTap: function (obj) {
    var that = this,
      cart_list = this.data.cart_list;
    https.post('updateGoodsCart', {
      cart_list: cart_list
    }, true).then(res => {
      that.setData({
        cart_ids: res
      })
      that.goSumbit();
    })
  },
  /**
   * @xk 提交订单
   */
  goSumbit: function () {
    app.globalData.cart_id = this.data.cart_ids;
    wx.navigateTo({
      url: '/pages/goods_sure/goods_sure',
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.onShow();
  },
})